package com.zzy.java_gobang.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zzy.java_gobang.game.MatchRequest;
import com.zzy.java_gobang.game.MatchResponce;
import com.zzy.java_gobang.game.Matcher;
import com.zzy.java_gobang.game.OnlineUserManager;
import com.zzy.java_gobang.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;


@Component
public class MatchAPI extends TextWebSocketHandler {

    ObjectMapper objectMapper = new ObjectMapper();

    //下面的这个就是如果玩家进入大厅，把玩家键值对添加到onlineUserManager
    @Autowired
    private OnlineUserManager onlineUserManager;

    @Autowired
    private Matcher matcher=new Matcher();

    //下面的这个就是玩家上线的情况
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        try {
            //在游戏大厅的用户的信息
            User user = (User) session.getAttributes().get("user");


            WebSocketSession tempSession = onlineUserManager.getFromGameHall(user.getUserId());
            if (tempSession != null) {
                //针对这个情况，我们需要告诉客户端：不可重复登录
                //session.sendMessage(new TextMessage(objectMapper.writeValueAsString(user)));
                MatchResponce response = new MatchResponce();
                response.setOk(false);
                response.setReason("禁止多开");
                session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
                session.close();
                return;
            }


            //拿到信息之后，设置在线状态
            onlineUserManager.enterGameHall(user.getUserId(), session);
            System.out.println("玩家" + user.getUsername() + "进入游戏大厅");
        }
        catch (NullPointerException e) {
            e.printStackTrace();
            MatchResponce matchResponce = new MatchResponce();
            matchResponce.setOk(false);
            matchResponce.setReason("您没有登陆，无法匹配");
            //先通过mapper把response转换为字符串对象，然后进行包装，成为文本格式数据包
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(matchResponce)));
        }

    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        User user = (User) session.getAttributes().get("user");
        String payload = message.getPayload();
        //把数据载荷转换为这个java对象
        MatchRequest request = objectMapper.readValue(payload, MatchRequest.class);
        MatchResponce response = new MatchResponce();
        if(request.getMessage().equals("startMatch")){

            matcher.add(user);

            response.setOk(true);
            response.setMessage("stratMatch");
        }else if(request.getMessage().equals("stopMatch")){

            matcher.remove(user);
            //TODO 移除
            response.setOk(true);
            response.setMessage("stopMatch");
        }else{
            response.setOk(false);
            response.setReason("非法的请求");
        }
        session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
    }

    //下面的两个异常都是下线的情况
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {

        try {
            User user = (User)session.getAttributes().get("user");

            WebSocketSession tempSession = onlineUserManager.getFromGameHall(user.getUserId());
            if (tempSession == session) {
                onlineUserManager.exitGameHall(user.getUserId());
            }

            matcher.remove(user);
        }
        catch (NullPointerException e) {
            e.printStackTrace();
            MatchResponce matchResponce = new MatchResponce();
            matchResponce.setOk(false);
            matchResponce.setReason("您没有登陆，无法匹配");
            //先通过mapper把response转换为字符串对象，然后进行包装，成为文本格式数据包
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(matchResponce)));
        }

    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        try {
            User user = (User)session.getAttributes().get("user");

            WebSocketSession tempSession = onlineUserManager.getFromGameHall(user.getUserId());
            if (tempSession == session) {
                onlineUserManager.exitGameHall(user.getUserId());
            }

            matcher.remove(user);
        }
        catch (NullPointerException e) {
            e.printStackTrace();
            MatchResponce matchResponce = new MatchResponce();
            matchResponce.setOk(false);
            matchResponce.setReason("您没有登陆，无法匹配");
            //先通过mapper把response转换为字符串对象，然后进行包装，成为文本格式数据包
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(matchResponce)));
        }
    }
}
